use crate::mdb;
use axum::Json;
use futures_util::io::AsyncReadExt;
use mongodb::options::{GridFsBucketOptions, GridFsDownloadByNameOptions};
use serde_json::Value;

use super::prefix;
use crate::base64;
// 获取文件内容
pub async fn download(filename:&str, bucket:&str) -> Result<Option<String>, Json<Value>>{
    let conn = mdb::connect().await?;

    let options = GridFsBucketOptions::builder().bucket_name(bucket.to_string()).build();

    let bucket = conn.gridfs_bucket(options);

    let stream_options = GridFsDownloadByNameOptions::builder( ).build( );
    let stream = bucket.open_download_stream_by_name(filename).with_options(stream_options).await;

    match stream {
        Ok(mut f) => {
            let mut buf:Vec<u8> = Vec::new();
            let _ = f.read_to_end(&mut buf).await.unwrap();
            let result = base64::encode(buf);
            Ok(Some(result))
        },
        Err(_e) => Ok(None)
    }
}
// 根据上传图片名称获取图片 base64
pub async fn download_base64(filename:&str, bucket:&str) -> Result<Option<String>, Json<Value>>{
    let url = download( &filename, bucket ).await?;
    match url {
        Some(f) => Ok( Some(prefix::get_prefix(filename)? + &f) ),
        None => Ok(None)
    }
}